package com.csdj.t301.cloud.uitls;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.print.Doc;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * author:cloud
 * date:2021/1/25 0025
 **/
public class DomUtils {

    public static void main(String[] args) {
        //创建工厂类
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {
            //创建文档建建类
            DocumentBuilder documentBuilder = factory.newDocumentBuilder();
            //加载文档
            Document document = documentBuilder.parse("resources/xml/phoneInfo.xml");
            //添加标签
            appendTag(document,"type");
            //保存到文件
            saveXml(document,"newphone.xml");

        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void appendTag(Document doc,String tagName){
        Element newEle = doc.createElement(tagName);
        newEle.setAttribute("screen","6.0");
        newEle.setAttribute("name","iphonex");
//        Element iphone = (Element) doc.getElementsByTagName("test").item(0);
        Element iphone = doc.getElementById("iphone");
        iphone.appendChild(newEle);
    }

    /**
     * 保存xml文件
     * @param doc
     * @param filename
     */
    public static void saveXml(Document doc,String filename){
        TransformerFactory factory = TransformerFactory.newInstance();
        try {
            Transformer transformer = factory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new FileOutputStream(filename));
            transformer.transform(source,result);
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        }
    }
}
